<?php

/**
 * Name: 主管审核记录仓储层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:30:00
 */

namespace App\Repositories\Checkin;

use App\Models\Checkin\SupervisorReview;
use App\Repositories\BaseRepository;
use Illuminate\Support\Arr;

class SupervisorReviewRepository extends BaseRepository
{
    public function __construct(SupervisorReview $model)
    {
        parent::__construct($model);
    }

    /**
     * 创建或更新记录
     */
    public function updateOrCreate(array $attributes, array $values = [])
    {
        return $this->model->updateOrCreate($attributes, $values);
    }

    /**
     * 检查主管今天是否已经审核过指定班组
     */
    public function hasReviewedTeamToday($supervisorId, $teamName, $date = null)
    {
        $date = $date ?: today();

        return $this->query()
            ->where('supervisor_id', $supervisorId)
            ->where('team_name', $teamName)
            ->where('review_date', $date)
            ->exists();
    }

    /**
     * 检查主管今天是否已经审核过
     */
    public function hasReviewedToday($supervisorId, $date = null)
    {
        $date = $date ?: today();

        return $this->query()
            ->where('supervisor_id', $supervisorId)
            ->where('review_date', $date)
            ->exists();
    }

    /**
     * 获取主管对指定班组的审核记录
     */
    public function getSupervisorTeamReview($supervisorId, $teamName, $date)
    {
        return $this->query()
            ->with('supervisor')
            ->where('supervisor_id', $supervisorId)
            ->where('team_name', $teamName)
            ->where('review_date', $date)
            ->first();
    }

    /**
     * 获取主管当天的审核记录
     * 用于检查主管是否已审核
     */
    public function getSupervisorReview($supervisorId, $date)
    {
        return $this->query()
            ->with('supervisor')
            ->where('supervisor_id', $supervisorId)
            ->where('review_date', $date)
            ->where('review_status', '!=', SupervisorReview::STATUS_PENDING)
            ->first();
    }

    /**
     * 创建或更新主管审核记录
     */
    public function createOrUpdateReview($supervisorData, $reviewData, $date = null)
    {
        $date = $date ?: today();

        // 处理 leader_review_ids：将逗号分隔的字符串转换为整数数组
        if (isset($reviewData['leader_review_ids']) && is_string($reviewData['leader_review_ids'])) {
            $ids = explode(',', $reviewData['leader_review_ids']);
            $ids = array_filter($ids, function($value) {
                return trim($value) !== '';
            });
            $ids = array_map('intval', $ids);
            $reviewData['leader_review_ids'] = array_values($ids); // 重置数组键，确保是 [0, 1, 2...]
        }

        // 排除不需要的字段（date 和 team_name）
        $data = array_merge(Arr::except($reviewData, ['date', 'team_name']), [
            'review_date' => $date,
            'supervisor_id' => $supervisorData['id'],
            'supervisor_name' => $supervisorData['name'],
            'reviewed_at' => now(),
        ]);

        return $this->updateOrCreate([
            'supervisor_id' => $supervisorData['id'],
            'review_date' => $date,
        ], $data);
    }

    /**
     * 获取待审核的班组列表
     */
    public function getPendingReviews($date = null, $supervisorId = null)
    {
        $date = $date ?: today();

        $query = $this->query()
            ->with('supervisor')
            ->where('review_date', $date)
            ->where('review_status', SupervisorReview::STATUS_PENDING);

        if ($supervisorId) {
            $query->where('supervisor_id', $supervisorId);
        }

        return $query->get();
    }

    /**
     * 获取主管的审核记录列表
     */
    public function getSupervisorReviews($supervisorId, $perPage = 15, $filters = [])
    {
        $query = $this->query()->with('supervisor')->where('supervisor_id', $supervisorId);

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('review_date', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('review_date', '<=', $filters['end_date']);
        }

        // 班组筛选
        if (isset($filters['team_name'])) {
            $query->where('team_name', $filters['team_name']);
        }

        // 状态筛选
        if (isset($filters['status'])) {
            $query->where('review_status', $filters['status']);
        }

        return $query->orderBy('review_date', 'desc')
                    ->orderBy('team_name')
                    ->paginate($perPage);
    }

    /**
     * 获取指定日期的所有主管审核记录
     */
    public function getDailyReviews($date)
    {
        return $this->query()
            ->where('review_date', $date)
            ->with('supervisor')
            ->get()
            ->groupBy('team_name');
    }

    /**
     * 获取异常审核记录
     */
    public function getAbnormalReviews($date, $teamName = null, $supervisorId = null)
    {
        $query = $this->query()
            ->with('supervisor')
            ->where('review_date', $date)
            ->where('review_status', SupervisorReview::STATUS_REJECTED);

        if ($teamName) {
            $query->where('team_name', $teamName);
        }

        if ($supervisorId) {
            $query->where('supervisor_id', $supervisorId);
        }

        return $query->get();
    }

    /**
     * 获取所有班组的审核状态
     */
    public function getTeamsReviewStatus($date, $teams = null)
    {
        $query = $this->query()->with('supervisor')->where('review_date', $date);

        if ($teams && is_array($teams)) {
            $query->whereIn('team_name', $teams);
        }

        return $query->get()->keyBy('team_name');
    }
}

